<template>
  <!-- 头部搜索框 -->
  <el-form :model="queryForm" :inline="true">
    <el-form-item label="用户名" >
      <el-input v-model="queryForm.username" />
    </el-form-item>
    <el-form-item label="电子邮件">
      <el-input v-model="queryForm.email" />
    </el-form-item>
    <el-form-item label=''>
      <el-select v-model="queryForm.sex" placeholder="性别" style="width: 80px">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="queryForm.mobile" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="handleRest">重置</el-button>
    </el-form-item>
    <el-form-item style="margin-left: 125px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleRemove(0)">删除</el-button>
    </el-form-item>
  </el-form>
  <!-- 列表 -->
  <el-table :data="tableData" style="width: 98%" row-key="id" default-expand-all @selection-change="handleSelectionChange" height="600px">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="55" />
    <el-table-column prop="id" label="用户ID" width="200" />
    <el-table-column prop="username" label="用户名" width="150" />
    <el-table-column prop="nickname" label="用户昵称" width="150" />
    <el-table-column prop="sex" label="性别" width="100" show-overflow-tooltip>
      <template #default="{ row }">
        <span v-if="row.sex=== 1">女</span>
        <span v-else-if="row.sex === 0">男</span>
      </template>
    </el-table-column>
    <el-table-column prop="avatar" label="头像" width="200">
      <template #default="{ row }">
        <el-avatar shape="square" :size="80" :fit='fit' :src="row.avatar"/>
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="手机号" width="200" />
    <el-table-column prop="email" label="电子邮件" width="200" />
    <el-table-column prop="status" label="用户状态" width="150" >
    <template #default="{ row }">
      <span v-if="row.status=== 1">停用</span>
      <span v-else-if="row.status === 0">正常</span>
    </template>
    </el-table-column>
    <el-table-column prop="createUser" label="创建者" width="200" />
    <el-table-column prop="updateUser" label="更新者" width="200" />
    <el-table-column prop="createTime" label="创建日期" width="200" />
    <el-table-column prop="updateTime" label="更新日期" width="200" />
    <el-table-column prop="remark" label="备注" width="200" />
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <!-- v-if和v-show区别 -->
        <el-button link type="success" size="small" @click="handleEdit(scope.row.id)">修改</el-button>
        <el-button link type="danger" size="small" @click="handleRemove(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="pagination_container">
    <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
                   :page-sizes="[10, 20, 30, 40, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 新增和修改的弹窗 -->
  <el-dialog v-model="menuFormShow" :title="menuTitle" width="50%" :before-close="handleClose">
    <!-- 表单 -->
    <el-form :model="form" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="form.username">
            <el-input v-model="form.username" placeholder="请输入用户名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="form.password">
            <el-input v-model="form.password"
                      :disabled="pw"
                      placeholder="请输入密码"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="form.nickname">
            <el-input v-model="form.nickname" placeholder="请输入用户昵称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="form.sex">
            <el-select v-model="form.sex" placeholder="请选择性别" style="width: 200px">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号" prop="form.mobile">
            <el-input v-model="form.mobile" placeholder="请输入手机号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮件" prop="form.email">
            <el-input v-model="form.email" placeholder="请输入邮件"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="备注" prop="form.remark">
            <el-input v-model="form.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="form.status">
            <el-switch
                v-model="form.status"
                active-text="正常"
                inactive-text="停用"
                :active-value="0"
                :inactive-value="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" prop="form.avatar">
            <!--nginx代理 action="/api/upload"-->
            <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8081/upload"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="file"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar"  alt=""/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
            </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
import { reactive, toRefs } from 'vue'
import {Plus} from "@element-plus/icons-vue";

const pw = ref();

const token = sessionStorage.getItem('daocaoToken') || '';
const uploadHeaders = ref({ 'Daocao-Authorization' : token })
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    form.value.avatar = response.msg
  } else {
    ElMessage.error('Upload failed')
  }
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const state = reactive({
  fit : 'cover',
})
const { fit } = toRefs(state)

let total = ref(0);
let selectIds = ref([])

let menuFormShow = ref(false);
let menuTitle = ref("");

let queryForm = ref({
  username: undefined,
  nickname: undefined,
  email: undefined,
  mobile: undefined,
  sex : undefined,
  status : undefined,
  pageNum: 1,
  pageSize: 10
})

let form = ref({
  id : undefined,
  username : undefined,
  nickname : undefined,
  password : undefined,
  mobile : undefined,
  email : undefined,
  sex : undefined,
  status : undefined,
  avatar : undefined,
  remark : undefined,
})


const options = [
  {
    value: 0,
    label: '男',
  },
  {
    value: 1,
    label: '女'
  }
  ]

const tableData = ref([
])


onMounted(() => {
  getUserList()
});
const getUserList = () => {

  request.get(`/ums/sysuser/list/page`)
      .then(response => {
        tableData.value =response.data.data.list;
        total.value = response.data.data.total;
      })
}

// 重置
const handleRest = () => {
  const params = {
    username : undefined,
    nickname : undefined,
    email : undefined,
    mobile : undefined,
    sex : undefined,
    status : undefined,
    pageNum : queryForm.value.pageNum,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/sysuser/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}
// 搜索
const handleQuery = () => {
  const params = {
    username : queryForm.value.username,
    nickname : queryForm.value.nickname,
    email : queryForm.value.email,
    mobile : queryForm.value.mobile,
    sex : queryForm.value.sex,
    status : queryForm.value.status,
    pageNum : queryForm.value.pageNum,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/sysuser/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
          // 清空搜索框
          // queryForm.value = {}
        }
      })
}

const handleSizeChange = (sizeNumber) => {
  const params = {
    username : queryForm.value.username,
    nickname : queryForm.value.nickname,
    email : queryForm.value.email,
    mobile : queryForm.value.mobile,
    sex : queryForm.value.sex,
    status : queryForm.value.status,
    pageNum : queryForm.value.pageNum,
    pageSize : sizeNumber
  }
  request.get(`/ums/sysuser/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}
// 点击下一页，上一页
const handleCurrentChange = (pageNumber) => {
  const params = {
    username : queryForm.value.username,
    nickname : queryForm.value.nickname,
    email : queryForm.value.email,
    mobile : queryForm.value.mobile,
    sex : queryForm.value.sex,
    status : queryForm.value.status,
    pageNum : pageNumber,
    pageSize : queryForm.value.pageSize
  }
  request.get(`/ums/sysuser/list/page`, {params})
      .then(res => {
        if(res.data.code === 200) {
          // 获取数据
          tableData.value = res.data.data.list;
          total.value = res.data.data.total;
        }
      })
}

// 取消提交
const handleCancel = () =>{
  menuFormShow.value = false;
  form.value = {}
}

// 提交表单,根据form.id值判断是新增还是修改【有id值】
const handleSubmit = () => {
  // 做数据校验
  if(form.value.id) {
    // 修改
    request.put(`/ums/sysuser`, form.value)
        .then(res => {
          if(res.data.code === 200) {
            // 关闭窗口
            menuFormShow.value = false;
            // 刷新列表
            getUserList();
            //清除回显数据
            form.value = {};
            // 弹窗提示新增成功
            ElMessage({
              message: '修改用户信息成功！',
              type: 'success',
            })
          }else{
            // 弹窗提示新增失败
            ElMessage({
              message: '修改用户信息失败！',
              type: 'error',
            })
          }
        })
  }else {
    // 新增，调用新增接口
    request.post(`/ums/sysuser`,form.value)
        .then(res => {
          console.log("res=======>",res);
          if(res.data.code === 200) {
            // 关闭窗口
            menuFormShow.value = false;
            // 刷新列表
            getUserList();
            //清除回显数据
            //form.value = {};
            // 弹窗提示新增成功
            ElMessage({
              message: '新增用户成功！',
              type: 'success',
            })
        }
    })
  }
}

// 新增按钮，弹出表单
const handleAdd = () => {
  pw.value = false;
  menuFormShow.value = true;
  menuTitle.value = "新增用户";
}
// 修改按钮，根据id查询对应的数据，弹出表单，回显数据
const handleEdit = (id) => {
  // 先查询数据，再弹窗
  request.get(`/ums/sysuser/byOne?userId=${id}`)
      .then(res => {
        if(res.data.code === 200) {
          // 保障后端返回的字段名和前端字段名相同，可以一一赋值
          form.value = res.data.data;
          pw.value=true;
          menuFormShow.value = true;
          menuTitle.value = "修改用户信息";
        }else {
          ElMessage({
            message: '数据查询失败！',
            type: 'error',
          })
        }
  })

}

// 多选变化
const handleSelectionChange = (selection) => {
  let ids = selection.map(item => item.id)
  selectIds.value = ids;
}

// 删除按钮，弹出是否要删除数据，确定就删除，取消就不删除
const handleRemove = (id) => {
  // 走删除接口
  let ids = undefined;
  if(id > 0) {
    ids = [id]
  }else {
    ids = selectIds.value;
  }
  // id其实是点击操作下的删除按钮时才会有数据
  ElMessageBox.confirm(
      `确定要删除{${ids}}数据吗?`,
      '删除用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        request.delete(`/ums/sysuser?ids=${ids}`)
            .then(res => {
          if(res.data.code === 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
            // 刷新列表
            getUserList();
          }
        })
      })
      .catch(() => {
      })
}

// 关闭弹窗
const handleClose = () => {
  menuFormShow.value = false;
  form.value = {}
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style lang="scss" scoped>
.pagination_container {
  position: relative;
  height: 40px;
  margin-top: 15px;

}

.el-pagination {
  position: absolute;
  right: 110px;
}

.demo-fit {
  display: flex;
  text-align: center;
  justify-content: space-between;
}
.demo-fit .block {
  flex: 1;
  display: flex;
  flex-direction: column;
  flex-grow: 0;
}

.demo-fit .title {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

</style>
